package com.ykzhujiang.lovespirit.parser;

import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ykzhujiang.lovespirit.entity.LThread;
import com.ykzhujiang.lovespirit.entity.Notice;
import com.ykzhujiang.lovespirit.util.Utility;

public class TongjiParser extends Parser {
	public TongjiParser() {

		resource_root = "http://bbs.tongji.edu.cn/";
		resource_pattern = "(?<=<img src=\"/)(bbscon\\.php\\?.*?)(?=\")";
		writer_pattern = "(?<=发信人: )(.+)(?=,)";
		title_pattern = "(?<=标  题: )(.+)(?=\\r\\n)";
		board_pattern = "(?<=信区: )(.+)(?=\\r\\n)";
		site_pattern = "(?<=发信站: )(.+)(?= \\()";
		content_pattern = "(?<= \\d{4}\\)(.{1,8})?\\r\\n)((?s).*?)(?=(※ 修改:·)|(※ 来源:·同舟共济站)|\\z)";
		date_pattern = "(?<=\\()((\\w{3}) (\\w{3}) {1,2}(\\w{1,2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4}))(?=\\)(.{1,8})?\\r\\n)";
		notice_pattern = "(?<=src=\"/)(jscon.php?.*?)(?=\")";
	}

	public int ParseDate(String text, Notice notice) {
		Pattern p = Pattern.compile(date_pattern);
		Matcher m = p.matcher(text);
		int year, month, date, hour, min, sec;
		if (m.find()) {
			year = Integer.parseInt(m.group(8));
			month = Utility.GetMonth(m.group(3));
			date = Integer.parseInt(m.group(4));
			hour = Integer.parseInt(m.group(5));
			min = Integer.parseInt(m.group(6));
			sec = Integer.parseInt(m.group(7));
			Calendar c=notice.getCalDate();
			c.set(year, month, date, hour, min, sec);
			notice.setCalDate(c);
		}
		return 0;
	}

	public LThread Parse(String url_text, String text) {
		if(text==null)
			return null;
		lthread = new LThread();
		Pattern p = Pattern.compile(notice_pattern);
		Matcher m = p.matcher(text);
		while (m.find()) {
			String text_single = Utility.GetURLText(url_root + m.group(1),
					connect_times);
			if(text_single==null)
				continue;
			text_single = RemoveJS(text_single);
			lthread.notices.add(ParseSingle(url_text, text_single));
		}
		if(lthread.notices.size()==0)
			return null;
		return lthread;
	}

	public String RemoveJS(String text) {
		StringBuffer sb = new StringBuffer();
		Pattern p = Pattern.compile(js_pattern);
		Matcher m = p.matcher(text);
		while (m.find()) {
			sb.append(m.group(1).replaceAll("&nbsp;", " ").replaceAll("&amp;",
					"&"));
			sb.append("\r\n");
		}
		return sb.toString();
	}

	private String js_pattern = "(?<=document\\.write\\(')(.*?)(?='\\);)";

	private String url_root = "http://bbs.tongji.edu.cn/";

	private int connect_times = 3;
}
